package com.ias.agdis_r.activity.mine;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseKeyListActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.adapter.FlightStateHistoryAdapter;
import com.ias.agdis_r.bean.fight.FlightChanged;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.RestfulUri;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponseHeader;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.request.FlightChangeRequest;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.response.FlightChangeResponse;
import com.ias.agdis_r.terminalmanager.restful.flight.vo.FlightInfoChangedsVO;
import com.ias.agdis_r.util.SecurityUtil;
import com.ias.agdis_r.util.flight.UiUtil;
import com.ias.agdis_r.volley.GsonRequest;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorAdapter;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorListener;
import com.ias.agdis_r.volley.callback.BaseOnVolleySuccessListener;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;

import me.maxwin.view.XListView;

/**
 * 航班变更记录
 * 
 * @author qibo.yu
 *
 */
public class FlightStateHistoryActivity extends BaseKeyListActivity implements XListView.IXListViewListener, View.OnClickListener {

	public static final String EXTRA_FLIGHT_FKE = "FlightStateHistoryActivity_fke";
	public static final String EXTRA_FLIGHT_FLN = "FlightStateHistoryActivity_fln";

	/** 服务器时间格式 */
	private static final SimpleDateFormat TIME_DATE_FORMATE = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.CHINA);

	private ActionBar actionBar;
	private XListView mListView;
	private List<FlightChanged> data = new LinkedList<FlightChanged>();
	private BaseAdapter mAdapter;

	private TextView tStartDate, tStartTime;

	private RequestQueue requestQueue;
	private FlightChangeRequest flightChangeRequest;

	private String fke;
	private Calendar time = Calendar.getInstance();

	private boolean isRefresh = false;

	private BaseOnVolleySuccessListener<FlightChangeResponse> onSuccessCallback = new BaseOnVolleySuccessListener<FlightChangeResponse>() {

		@Override
		public void onRequestSuccess(FlightChangeResponse response) {
			data.clear();
			FlightInfoChangedsVO changedsVO = response.getFlightInfoChangedsVO();
			if (changedsVO != null) {
				data.addAll(changedsVO.getFlightInfoChangeds());
				Collections.reverse(data);
			}
			mAdapter.notifyDataSetChanged();

			onDataLoaded();
		}

		@Override
		public void onRequestFailed(BaseResponseHeader header) {
			data.clear();
			mAdapter.notifyDataSetChanged();
			onDataLoaded();
		}
	};

	private BaseOnVolleyErrorListener onErrCallback = new BaseOnVolleyErrorAdapter() {
		@Override
		public void onErrorOccurred(com.android.volley.VolleyError resp) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.serviceError), false);
			onDataLoaded();
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_flight_state_history);

		actionBar = getActionBar();
		initActionBarFlightHistory();

		fke = getIntent().getStringExtra(EXTRA_FLIGHT_FKE);

		System.out.println("fke:" + fke);

		requestQueue = Volley.newRequestQueue(this);
		initView();
		initEvent();
		loadData();
	}

	private void initEvent() {
		tStartDate.setOnClickListener(this);
		tStartTime.setOnClickListener(this);
	}

	private void refresh() {
		mListView.startRefreshView();
		isRefresh = true;
		loadData();
	}

	private void loadData() {
		if (!isRefresh) {
			UiUtil.showLoadingUi(this);
		}
		if (flightChangeRequest == null) {
			initFlightChangeRequest();
		}
		flightChangeRequest.setTime(TIME_DATE_FORMATE.format(time.getTime()));

		Request<FlightChangeResponse> request = null;
		try {
			request = new GsonRequest<FlightChangeResponse>(
                    RestfulUri.getUri(MessageModel.DYHI), FlightChangeResponse.class,
                    DataManager.getInstance().getMapper().writeValueAsString(flightChangeRequest), this.onSuccessCallback, this.onErrCallback);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		requestQueue.add(request);
	}

	private void onDataLoaded() {
		UiUtil.removeLoadingUiIfExist(this);

		String str = getFormatedTimeForHearder();

		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime(str);
	}

	/**
	 * 获取格式化的当前时间
	 * 
	 * @return时间格式“HH:mm:ss”
	 */
	@SuppressLint("SimpleDateFormat")
	private String getFormatedTimeForHearder() {
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
		Date curDate = new Date(System.currentTimeMillis());
		return formatter.format(curDate);
	}

	private void initView() {
		mListView = (XListView) getListView();
		mListView.setXListViewListener(this);
		mListView.setPullLoadEnable(false);
		Collections.reverse(data);
		mAdapter = new FlightStateHistoryAdapter(this, data);
		mListView.setAdapter(this.mAdapter);

		tStartDate = (TextView) findViewById(R.id.flight_history_day);
		tStartTime = (TextView) findViewById(R.id.flight_history_time);
	}

	private void initFlightChangeRequest() {
		if (flightChangeRequest == null) {
			flightChangeRequest = new FlightChangeRequest();
		}
		flightChangeRequest.setHeader(SecurityUtil.getCommonRequestHeaderObject(MessageModel.DYHB));
		flightChangeRequest.setFlg("N");
		flightChangeRequest.setFke(fke);

		time.add(Calendar.YEAR, -3);
		updateTimeView(time.getTime());

		flightChangeRequest.setTime(TIME_DATE_FORMATE.format(time.getTime()));
	}

	@Override
	public void onRefresh() {
		isRefresh = true;
		loadData();
	}

	@Override
	public void onLoadMore() {

	}

	@SuppressLint("InflateParams")
	private void initActionBarFlightHistory() {
		// TODO Auto-generated method stub
		actionBar.setCustomView(
				LayoutInflater.from(FlightStateHistoryActivity.this).inflate(R.layout.actionbar_back_and_home, null));
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
		TextView title = (TextView) findViewById(R.id.txt_title);
		title.setText(R.string.FlightStateHistoryActivity);
		ImageView back = (ImageView) findViewById(R.id.action_back);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		View home = findViewById(R.id.action_home);
		home.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(FlightStateHistoryActivity.this, MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.flight_history_day:
			selectDate();
			break;
		case R.id.flight_history_time:
			selectTime();
			break;
		default:
			break;
		}

	}

	/**
	 * 更新界面时间元素
	 * 
	 * @param date
	 */
	private void updateTimeView(Date date) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
		SimpleDateFormat dateFormat2 = new SimpleDateFormat("hh:mm", Locale.CHINA);
		tStartDate.setText(dateFormat.format(date));
		tStartTime.setText(dateFormat2.format(date));
	}

	/**
	 * 选择时间
	 */
	private void selectTime() {
		TimePickerDialog timePickerDialog = new TimePickerDialog(this, new OnTimeSetListener() {

			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				time.set(Calendar.HOUR_OF_DAY, hourOfDay);
				time.set(Calendar.MINUTE, minute);
				updateTimeView(time.getTime());
				refresh();
			}
		}, time.get(Calendar.HOUR_OF_DAY), time.get(Calendar.MINUTE), false);
		timePickerDialog.setCancelable(true);
		timePickerDialog.show();

	}

	/**
	 * 选择日期
	 */
	private void selectDate() {
		DatePickerDialog datePickerDialog = new DatePickerDialog(this, new OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				time.set(Calendar.YEAR, year);
				time.set(Calendar.MONTH, monthOfYear);
				time.set(Calendar.DAY_OF_MONTH, dayOfMonth);
				updateTimeView(time.getTime());
				refresh();
			}
		}, time.get(Calendar.YEAR), time.get(Calendar.MONTH), time.get(Calendar.DAY_OF_MONTH));
		datePickerDialog.setCancelable(true);
		datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
		// 三天的历史变更可查
		// datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()
		// - 1000 * 60 * 60 * 24 * 3);
		datePickerDialog.show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(null != requestQueue)
		requestQueue.stop();
	}
}
